<template>
  <ContentWrap>
    <!-- 顶部项目信息 -->
    <div class="project-header mb-16">
      <div class="project-title">
        <span class="title">任务名称：{{ detailData.taskName }}</span>

        <span class="project-no ml-16">任务编号：{{ detailData.taskNumber }}</span>
        <el-tag v-if="detailData.taskFinishStatus === 1" type="success" class="ml-8">已完成</el-tag>
        <el-tag v-else-if="detailData.taskFinishStatus === 2" type="danger" class="ml-8">已终止</el-tag>
        <el-tag v-else type="info" class="ml-8">未完成</el-tag>
      </div>
      <!-- <div class="project-meta mt-8">
        <span class="mr-24">创建人：{{ detailData.userName }}</span>
        <span class="mr-24">创建时间：{{ formatDate(detailData.createTime, 'YYYY-MM-DD HH:mm:ss') }}</span>
        <span class="mr-24">修改时间：{{ formatDate(detailData.updateTime, 'YYYY-MM-DD HH:mm:ss') }}</span>
      </div> -->
    </div>
    <div>
        <el-card>
          <el-descriptions :column="3" border> 
            <el-descriptions-item label="发起人">
              {{ detailData.userName }}
            </el-descriptions-item>
            <el-descriptions-item label="发起日期">
              {{ formatDate(detailData.createTime, 'YYYY-MM-DD') }} 
            </el-descriptions-item> 
            <el-descriptions-item label="任务类型">
              <dict-tag :type="DICT_TYPE.OA_TASK_TYPE" :value="detailData.taskType" />
            </el-descriptions-item>
            <el-descriptions-item label="收费金额">
              {{ detailData.paymentAmount }}
            </el-descriptions-item>

           <template v-if="detailData.taskFinishStatus === 1"> 
              <el-descriptions-item :rowspan="2" label="是否收款">
                <dict-tag :type="DICT_TYPE.OA_IS_OR_NO" :value="detailData.paymentReceived" />
              </el-descriptions-item>
              <template v-if="detailData.paymentReceived == 0" >
                <el-descriptions-item :rowspan="2" :span="2" label="未收款原因">
                  {{ detailData.notPayReason }}
                </el-descriptions-item>
              </template>
              <template v-else>
                <el-descriptions-item label="收款方式">
                  <dict-tag :type="DICT_TYPE.OA_PAY_METHOD" :value="detailData.paymentMethod" />
                </el-descriptions-item>
                <el-descriptions-item label="收费金额">
                  {{ detailData.paymentAmount }}
                </el-descriptions-item>
                <el-descriptions-item label="收款日期">
                   {{ formatDate(detailData.paymentDate, 'YYYY-MM-DD') }} 
                </el-descriptions-item> 
                <el-descriptions-item label="收款公司">
                  {{ detailData.collectionCompany }}
                </el-descriptions-item>
                <el-descriptions-item :rowspan="2"   label="是否开票">
                  <dict-tag :type="DICT_TYPE.OA_IS_OR_NO" :value="detailData.isInvoiced" />
                </el-descriptions-item>
              <template v-if="detailData.isInvoiced == 0" >
                  <el-descriptions-item :rowspan="2" :span="2" label="未开票原因">
                    {{ detailData.notInvoicedReason }}
                  </el-descriptions-item>
                </template>
                <template v-else>
                    <el-descriptions-item label="开票方">
                      {{ detailData.invoicedCompany }}
                    </el-descriptions-item>
                    <el-descriptions-item label="收票方">
                      {{ detailData.payee }}
                    </el-descriptions-item>
                    <el-descriptions-item label="开票日期">
                      {{ formatDate(detailData.invoicedDate, 'YYYY-MM-DD') }} 
                    </el-descriptions-item>
                </template> 
              </template> 
           </template>
           <template v-else-if="detailData.taskFinishStatus === 2">
              <el-descriptions-item :rowspan="2" label="终止原因">
                {{ detailData.terminationReason }}
              </el-descriptions-item>
            </template> 
          </el-descriptions>
        </el-card>

         <el-card class="mt-24" style="min-height: 300px;">
            <template #header>
              沟通信息
              <el-button size="small"  v-hasPermi="['oa:main-tasks:update']"  link  
              v-if="detailData.taskFinishStatus === 0&&(detailData.status==1 || detailData.status==2)" type="primary" @click="dialogRemarkVisible = true; detailDataRemark = detailData.remark">
                  <Icon class="mr-1px" icon="ep:edit" />  更新沟通信息
              </el-button>
            </template> 
          {{ detailData.remark }}
         </el-card>

        <OaFileManager class="mt-24" :header="detailData.taskFinishStatus === 0"  :initial-file-ids="detailData.files" @file-select-success="handleFileSelect" />
        
        <!-- 文件保存按钮 -->
        <div v-if="filesChanged && detailData.taskFinishStatus === 0" class="mt-3 text-center">
          <el-button type="primary" @click="handleSaveFiles" :loading="saveFilesLoading">
            <Icon class="mr-1px" icon="ep:upload" /> 保存文件
          </el-button>
        </div>

        <el-card class="mt-24" shadow="hover">
           <div class="mb-3">
              <el-button type="primary" :disabled="subTaskzDisabled" v-if="detailData.taskFinishStatus === 0" @click="openAddSubtask">新增子任务</el-button>
            </div>
            <el-table v-loading="subTasksLoading" :data="subTasksList" :stripe="true" :show-overflow-tooltip="true">
              <!-- <el-table-column label="序号" align="center" prop="id" /> -->
              <el-table-column label="子任务名称" align="center" prop="taskTitle"  width="200">
                <template #default="scope">
                  <el-link type="primary" @click="openViewSubtask(scope.row.id)">{{ scope.row.taskTitle }}</el-link>
                </template>
              </el-table-column>
              <el-table-column label="执行人" align="center" prop="operatorUserName" />
              <!-- <el-table-column label="优先级" align="center" prop="priorityType">
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.OA_PRIORITY_TYPE" :value="scope.row.priorityType" />
                </template>
              </el-table-column> -->
            
              <el-table-column label="任务状态" align="center" prop="taskStatus">
                <template #default="scope">
                  <dict-tag :type="DICT_TYPE.OA_TASK_STATUS" :value="scope.row.taskStatus" />
                </template>
              </el-table-column>
              <el-table-column label="进度描述" align="center" prop="reason" >
                <template #default="scope">
                  <span v-if="scope.row.taskStatus==2">{{ scope.row.reason }}</span>
                  <span v-else>{{ scope.row.taskDescription }}</span>
                </template>
              </el-table-column>
              <el-table-column label="发起人" align="center" prop="createName" />
              <el-table-column label="结束日期" align="center" prop="endDate" width="110">
                <template #default="scope">
                  <span>{{ scope.row.endDate }}</span>
                  <el-text v-if="isOverdue(scope.row.endDate, scope.row.taskStatus)" type="danger" class="ml-4">
                    已逾期{{ getOverdueDays(scope.row.endDate) }}天
                  </el-text>
                </template>
              </el-table-column>
              <el-table-column label="实际完成日期" align="center" prop="actualEndDate" width="110" />
              <el-table-column label="操作" align="center" fixed="right" width="320" v-if="detailData.taskFinishStatus === 0">
                <template #default="scope">
                  <!-- 只有在主任务未完成状态,只有执行人可以操作 完成子任务,完成主任务 -->
                  <template v-if="scope.row.operatorUserId === userStore.user.id"> 
                    <el-button type="primary" size="small" v-if="scope.row.taskStatus == 0" @click="openEditSubtask(scope.row.id)">
                      <Icon class="mr-1px" icon="ep:edit" /> 修改 </el-button>
                    <el-button type="success"  size="small" v-if="scope.row.taskStatus == 0" @click="handleFinishSubtask(scope.row.id,1)">
                      <Icon class="mr-1px" icon="ep:circle-check-filled" /> 完成</el-button>
                    <el-button type="warning"  size="small" v-if="scope.row.taskStatus == 0" @click="openRejectDialog(scope.row)">
                      <Icon class="mr-1px" icon="ep:failed" /> 拒绝</el-button>
                    <el-button type="primary" size="small" v-if="scope.row.taskStatus !== 0" @click="handleFinishSubtask(scope.row.id,0)">
                      <Icon class="mr-1px" icon="ep:back" />回退</el-button>
                  </template>

                  <!-- 未完成的任务可以删除,但是必须是创建人有权限 -->
                  <el-button type="danger"  size="small" v-hasPermi="['oa:subtasks:delete']"   v-if="scope.row.taskStatus == 0 && scope.row.creator == userStore.user.id"   @click="handleDeleteSubtask(scope.row.id)">
                    <Icon class="mr-1px m-b-1px" :size="14" icon="ep:delete-filled" />删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <SubtasksForm ref="subtasksFormRef" @success="getSubTasksList" />
            <!-- 拒绝理由弹窗 -->
            <el-dialog v-model="showRejectDialog" title="拒绝理由" width="400px">
              <el-form>
                <el-form-item label="理由" required>
                  <el-input
                    v-model="rejectReason"
                    type="textarea"
                    :rows="4"
                    maxlength="200"
                    show-word-limit
                    placeholder="请输入拒绝理由"
                  />
                </el-form-item>
              </el-form>
              <template #footer>
                <el-button @click="showRejectDialog = false">取消</el-button>
                <el-button type="primary" @click="submitRejectReason">确定</el-button>
              </template>
            </el-dialog>
        </el-card>
        <el-card class="mt-24">
          <div class="mb-8"><b>任务完成率</b></div>
          <el-progress type="circle" :percentage="taskPercent" />
        </el-card>
        <el-card class="mt-24" v-if="false">
          <div class="mb-8"><b>任务燃尽图</b></div>
          <div id="burndownChart" style="width:100%;height:300px;"></div>
        </el-card>
    </div>
  
  </ContentWrap>

  <el-dialog title="更新沟通信息" :close-on-click-modal="false" v-model="dialogRemarkVisible">
    <el-input v-model="detailDataRemark" type="textarea" :rows="20" placeholder="请输入沟通信息" show-word-limit />
    <template #footer>
      <div  class="dialog-footer">
        <el-button @click="dialogRemarkVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRemark">确 定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { DICT_TYPE } from '@/utils/dict'
import { useUserStore } from '@/store/modules/user'
import { formatDate } from '@/utils/formatTime'
import { propTypes } from '@/utils/propTypes'
import { MainTasksApi, MainTasksVO } from '@/api/oa/maintasks'
import { SubtasksApi, SubtasksVO } from '@/api/oa/subtasks'
import * as FileApi from '@/api/infra/file'
import * as echarts from 'echarts'
import SubtasksForm from '@/views/oa/subtasks/SubtasksForm.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Editor } from '@/components/Editor'
import { getSimpleUserListByIds } from '@/api/system/user'
import UserSelect from '@/views/system/user/UserSelect.vue' 
import dayjs from 'dayjs' 
import { de } from 'element-plus/es/locale'
import { template } from 'lodash-es'

defineOptions({ name: 'OaMainTasksDetail' })

const userStore = useUserStore() 

interface FileInfo {
  id: number
  title: string
  url: string
}

const { query } = useRoute() // 查询参数
const props = defineProps({
  id: propTypes.number.def(undefined),
  subTaskzDisabled: {
    type: Boolean,
    default: false,
  }
})
const emit = defineEmits(['getTaskInfo'])
const activeTab = ref('mainTask') // 当前激活的Tab
const detailLoading = ref(false) // 表单的加载中
const detailData = ref<any>({}) // 详情数据
const fileList = ref<FileInfo[]>([]) // 文件列表
const queryId = query.id as unknown as number // 从 URL 传递过来的 id 编号

// 文件保存相关
const filesChanged = ref(false) // 文件是否已变更
const saveFilesLoading = ref(false) // 保存文件加载状态
const originalFiles = ref<string>('') // 原始文件ID字符串

// 修改沟通内容
const dialogRemarkVisible = ref(false) 
const detailDataRemark = ref('') // 沟通内容



// 子任务列表相关
const subTasksLoading = ref(false) // 子任务列表的加载中
const subTasksList = ref<SubtasksVO[]>([]) // 子任务列表数据
const taskCount = ref({ totalTaskCount: 0, finishedTaskCount: 0 }) // 子任务统计数据

const subtasksFormRef = ref();

// 任务完成率
const taskPercent = computed(() => {
  if (!taskCount.value.finishedTaskCount || !taskCount.value.totalTaskCount) return 0
  return Math.round((taskCount.value.finishedTaskCount / taskCount.value.totalTaskCount) * 100)
})

const burndownData = ref([
  { date: '2024-05-01', remaining: 10 },
  { date: '2024-05-02', remaining: 8 },
  { date: '2024-05-03', remaining: 6 },
  { date: '2024-05-04', remaining: 4 },
  { date: '2024-05-05', remaining: 2 },
  { date: '2024-05-06', remaining: 0 }
]);

const renderBurndownChart = () => {
  const chartDom = document.getElementById('burndownChart');
  if (!chartDom) return;
  const myChart = echarts.init(chartDom);
  const option = {
    tooltip: { trigger: 'axis' },
    xAxis: { type: 'category', data: burndownData.value.map(i => i.date) },
    yAxis: { type: 'value', minInterval: 1 },
    series: [
      {
        name: '剩余任务数',
        type: 'line',
        smooth: true,
        data: burndownData.value.map(i => i.remaining),
        areaStyle: {},
        symbol: 'circle'
      }
    ]
  };
  myChart.setOption(option);
  window.addEventListener('resize', () => myChart.resize());
};

/** 获得主任务数据 */
const getInfo = async () => {
  detailLoading.value = true
  try {
    // 获取主任务详情
    detailData.value = await MainTasksApi.getMainTasks(props.id || queryId)

    // 获取子任务统计数据
    taskCount.value = await MainTasksApi.getSubtasksCount(props.id || queryId)

    // 处理文件列表
    if (detailData.value.files) {
      detailData.value.files = detailData.value.files.split(',') // 将文件 ID 字符串转换为数组
    }
    // 初始化原始文件状态
    originalFiles.value = detailData.value.files ? detailData.value.files.join(',') : ''
    filesChanged.value = false
    //获取子任务列表
    getSubTasksList()

    emit('getTaskInfo',detailData.value )
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    detailLoading.value = false
  }
}

/** 获得子任务列表 */
const getSubTasksList = async () => {
  subTasksLoading.value = true
  try {
    const data = await SubtasksApi.getSubtasksPageAll({
      pageNo: 1,
      pageSize: 100,
      mainTaskId: props.id || queryId
    })
    subTasksList.value = data.list 
  } finally {
    subTasksLoading.value = false
  }
}

const openAddSubtask = () => {
  subtasksFormRef.value.open('create', undefined, {
    id: detailData.value.id,
    taskName: detailData.value.taskName
  });
  nextTick(() => {
    if (subtasksFormRef.value?.formData) {
      subtasksFormRef.value.formData.mainTaskId = detailData.value.id;
      subtasksFormRef.value.formData.mainTaskName = detailData.value.taskName;
    }
  });
};

const openEditSubtask = (id: number) => {
  subtasksFormRef.value.open('update', id);
};

const openViewSubtask = (id: number) => {
  console.log('openViewSubtask', id)
  subtasksFormRef.value.open('preview', id);
};

// 监听Tab切换
watch(activeTab, (newVal) => {
  if (newVal === 'subTasks') {
    getSubTasksList()
  }
  if (newVal === 'mainTask') {
    nextTick(() => renderBurndownChart())
  }
  if (newVal === 'onlineDocs') {
    getOnlineDocsList();
  }
  if (newVal === 'teamMembers') {
    getTeamMembersList();
  }
})

defineExpose({ open: getInfo }) // 提供 open 方法，用于打开弹窗

/** 初始化 **/
onMounted(() => {
  getInfo()
  renderBurndownChart()
})

const onlineDocsList = ref<any[]>([]);
const onlineDocsLoading = ref(false);
const showDocDialog = ref(false);
const docDialogTitle = ref('新增文档');
const docForm = reactive({
  id: undefined,
  title: '',
  fileContent: ''
});
const docFormRef = ref();

const getOnlineDocsList = async () => {
  onlineDocsLoading.value = true;
  try {
    const files = await FileApi.getFilesByBiz(
      'mainTask',
      props.id || queryId
    );
    console.log(files)
    onlineDocsList.value = files;
  } finally {
    onlineDocsLoading.value = false;
  }
};

const openAddDoc = () => {
  docDialogTitle.value = '新增文档';
  Object.assign(docForm, { id: undefined, title: '', file_content: '' });
  showDocDialog.value = true;
};

const openEditDoc = (row: any) => {
  docDialogTitle.value = '编辑文档';
  Object.assign(docForm, { id: row.id, title: row.title, file_content: row.file_content });
  showDocDialog.value = true;
};

const submitDocForm = async () => {
  await docFormRef.value.validate();
  if (docForm.id) {
    await FileApi.updateDetail({
      ...docForm,
      id: props.id || queryId
    });
  } else {
    await FileApi.createFile({
      ...docForm,
      bizType: 'mainTask',
      fileClass: 5,
      bizId: props.id || queryId
    });
  }
  showDocDialog.value = false;
  getOnlineDocsList();
};

const handleDeleteDoc = async (row: any) => {
  await ElMessageBox.confirm('确定删除该文档吗？', '提示', { type: 'warning' });
  await FileApi.deleteFile(row.id);
  ElMessage.success('删除成功');
  getOnlineDocsList();
};

const teamMembersList = ref<any[]>([]);
const teamMembersLoading = ref(false);
const showAddMember = ref(false);
const selectedMemberIds = ref<number[]>([]);

const getTeamMembersList = async () => {
  teamMembersLoading.value = true;
  try {
    // 1. 获取主任务详情
    const mainTask = detailData.value;
    const applicantId = mainTask.userId;

    // 2. 获取所有子任务
    const subTasks = await SubtasksApi.getSubtasksPageAll({
      pageNo: 1,
      pageSize: 1000, // 假设不会超过1000条
      mainTaskId: mainTask.id
    });
    const operatorIds = subTasks.list
      .map((item: any) => item.operatorUserId)
      .filter((id: number) => !!id);

    // 3. 合并申请人和所有执行人，去重
    const allUserIds = Array.from(new Set([applicantId, ...operatorIds]));

    // 4. 获取用户详细信息
    const usersList = await getSimpleUserListByIds(allUserIds);

    // 5. 排序：申请人排第一，其余随意
    const sortedUsers = usersList.sort((a, b) => {
      if (a.id === applicantId) return -1;
      if (b.id === applicantId) return 1;
      return 0;
    });

    teamMembersList.value = sortedUsers;
  } finally {
    teamMembersLoading.value = false;
  }
};

const handleAddMembers = async () => {
  const oldIds = detailData.value.teamMembers
    ? detailData.value.teamMembers.split(',').map(id => Number(id))
    : [];
  const newIds = Array.from(new Set([...oldIds, ...selectedMemberIds.value]));
  await MainTasksApi.updateMainTasks({
    ...detailData.value,
    teamMembers: newIds.join(',')
  });
  showAddMember.value = false;
  selectedMemberIds.value = [];
  await getInfo();
  await getTeamMembersList();
};


const handleDeleteSubtask = async (id: number) => {
  await ElMessageBox.confirm('确定要删除该子任务吗？', '提示', { type: 'warning' });
  await SubtasksApi.deleteSubtasks(id);
  ElMessage.success('删除成功');
  getSubTasksList();
};

const handleFinishSubtask = async (id: number, taskStatus: number) => {
  await ElMessageBox.confirm('确定修改改子任务状态吗？', '提示', { type: 'warning' });
  await SubtasksApi.updateTasksStatus(id,2, taskStatus,'');
  getSubTasksList();
};

const isOverdue = (endDate: string, taskStatus: number) => {
  if (!endDate) return false;
  // 只对未完成的任务显示逾期
  const today = dayjs().startOf('day');
  const end = dayjs(endDate).startOf('day');
  return taskStatus !== 1 && today.isAfter(end);
};

const getOverdueDays = (endDate: string) => {
  if (!endDate) return 0;
  const today = dayjs().startOf('day');
  const end = dayjs(endDate).startOf('day');
  return today.diff(end, 'day');
};

const handleFileSelect = (fileIds: string[]) => {
  console.log(fileIds)
  // 1. 保存到 detailData 或表单
  detailData.value.files = fileIds.join(',')
  // 2. 检查文件是否变更
  const currentFiles = fileIds.join(',')
  filesChanged.value = currentFiles !== originalFiles.value
}

// 保存文件
const handleSaveFiles = async () => {
  if (!filesChanged.value) return
  
  saveFilesLoading.value = true
  try {
    // 构建完整的更新数据
    const updateData = {
      ...detailData.value,
      files: detailData.value.files
    }
    
    await MainTasksApi.updateMainTasks(updateData)
    
    // 更新原始文件状态
    originalFiles.value = detailData.value.files
    filesChanged.value = false
    
    ElMessage.success('文件保存成功')
  } catch (error) {
    console.error('保存文件失败:', error)
    ElMessage.error('保存文件失败')
  } finally {
    saveFilesLoading.value = false
  }
}

const showRejectDialog = ref(false)
const rejectReason = ref('')
const rejectSubtaskRow = ref<SubtasksVO | null>(null)

const openRejectDialog = (row: SubtasksVO) => {
  rejectSubtaskRow.value = { ...row }
  rejectReason.value = ''
  showRejectDialog.value = true
}

const submitRejectReason = async () => {
  if (!rejectReason.value.trim()) {
    ElMessage.warning('请填写拒绝理由')
    return
  }
  try {
    if (!rejectSubtaskRow.value || typeof rejectSubtaskRow.value.id !== 'number') {
      ElMessage.error('子任务数据异常')
      return
    }
    
    await SubtasksApi.updateTasksStatus(rejectSubtaskRow.value.id,2, 2,rejectReason.value);
    ElMessage.success('操作成功')
    showRejectDialog.value = false
    getSubTasksList()
  } catch (e) {
    // 错误处理
  }
}


const handleRemark = async () => {
    await MainTasksApi.updateMainTasks({
      id: detailData.value.id,
      remark: detailDataRemark.value
    })

    detailData.value.remark = detailDataRemark.value // 更新本地数据

    ElMessage.success('操作成功')
    dialogRemarkVisible.value = false;
}

 
</script>

<style scoped>
.project-header {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 12px;
  margin-bottom: 8px;
}

.project-title {
  font-size: 22px;
  font-weight: bold;
}

.project-no {
  color: #888;
}

.project-meta {
  font-size: 14px;
  color: #666;
}

.main-tabs {
  margin-bottom: 0;
}

.main-tabs :deep(.el-tabs__header) {
  margin-bottom: 0;
  border-bottom: 2px solid #3370ff;
  background: #f7faff;
  box-shadow: 0 2px 8px #f0f1f2;
  border-radius: 6px 6px 0 0;
}

.main-tabs :deep(.el-tabs__item) {
  text-align: center;
  justify-content: center;
  align-items: center;
  display: flex;
  font-weight: bold;
  font-size: 16px;
  color: #3370ff;
  padding: 12px 32px 10px 32px;
}

.main-tabs :deep(.el-tabs__item.is-active) {
  color: #fff;
  background: #3370ff;
  border-radius: 6px 6px 0 0;
}

.text-gray {
  color: #aaa;
}

.main-tabs :deep(.el-tabs__nav) {
  display: flex !important;
  justify-content: center !important;
  width: 100% !important;
}

.main-tabs :deep(.el-tabs__header) {
  display: flex;
  justify-content: center;
}

.mt-24 {
  margin-top: 24px;
}
</style>
